<?php
/**
 * 微信SDK
 * pan041ymail@gmail.com
 */

namespace app\index\controller;

vendor('qiniu.autoload');
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Processing\PersistentFop;

use think\Db;
use think\Exception;

class Weixin
{
    public $appid           = "";
    public $appsecret       = "";
    public $access_token    = "";

    /**
     * 构造函数
     */
    public function __construct($appid = NULL, $appsecret = NULL)
    {
        $res = Db::name('option')->where('option_name', 'wx')->find();

        $wxConfig = json_decode($res['option_value'], true);

        $this->appsecret    = $wxConfig['appsecret'];
        $this->appid        = $wxConfig['appid'];
        if ($appid) {
            $this->appid = $appid;
        }
        if ($appsecret) {
            $this->appsecret = $appsecret;
        }

    }

    /**
     * 发送模板消息
     * $openid              接收者openid       oTJius6kQ2hFOF66Dw0l5Xg-ICUM
     * $template_id         模板ID             BWrP-c1uXNvLvO-YNDtbVGVd0iiP7O3LibkzXkHirTI
     * $url                 详情跳转地址        http://www.qq.com
     * $data_arr            数据体             数组
     */
    public function sentMsg($openid, $template_id , $url = '' , $data_arr=[])
    {
        // 获取access_token
        $access_token = $this->getAccessToken();

        // 接口地址
        $api = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        // 模板参数
        $data['touser']         = $openid;
        $data['template_id']    = $template_id;
        $data['url']            = $url;

        // 模板数据
        $data['data']           = $data_arr;

        // 转json类型
        $data = json_encode($data);

        // 发送消息
        $res = $this->https_request($api, $data);
        $res = json_decode($res, true);
        if ($res['errcode'] != 0) {
            session('access_token', false);
        }

        return $res;
    }


    /**
     * 获取access_token
     */
    public function getAccessToken()
    {
        $token = false;

        $acc_token = Db::name('wxconfig')->where('name', 'access_token')->find();

        if ($acc_token && $acc_token['extend'] > time()) {

            $token = $acc_token['value'];

        } else {

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $res = $this->https_request($url);
            $res = json_decode($res, true);

            try {
                if ($res['access_token']) {

                    $update             = [];
                    $update['value']    = $res['access_token'];
                    $update['extend']   = time() + 7000;

                    Db::name('wxconfig')->where('name', 'access_token')->update($update);

                    $token = $res['access_token'];
                }
            } catch (Exception $exception) {

            }
        }

        return $token;
    }


    /**
     * 获取ticket
     */
    public function getTicket()
    {
        // 获取access_token
        $this->access_token = $this->getAccessToken();

        if (!$this->access_token) {
            echo 'access_token error';
            die;
        }

        $jsapi_ticket = false;

        $ticket = Db::name('wxconfig')->where('name', 'ticket')->find();

        if ($ticket && $ticket['extend'] > time()) {

            $jsapi_ticket = $ticket['value'];

        } else {

            $tick_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$this->access_token&type=jsapi";

            $res = $this->https_request($tick_url);
            $res = json_decode($res, true);

            try {
                if ($res['errmsg'] == 0) {

                    $update             = [];
                    $update['value']    = $res['ticket'];
                    $update['extend']   = time() + 7000;

                    Db::name('wxconfig')->where('name', 'ticket')->update($update);

                    $jsapi_ticket = $res['ticket'];
                }
            } catch (Exception $exception) {


            }
        }

        return $jsapi_ticket;
    }


    /**
     *
     */
    public function getTempVoice($id)
    {
        $this->access_token = $this->getAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $this->access_token . "&media_id=" . $id;

        //使用七牛抓取
        $qnConfig   = config('qiniu');
        $accessKey  = $qnConfig['ak'];
        $secretKey  = $qnConfig['sk'];
        $bucket     = $qnConfig['bk'];

        $auth = new Auth($accessKey, $secretKey);
        $bucketManager = new BucketManager($auth);

        $key_name = date('Ymd', time()) . '/' . $id;
        $key = $key_name . '.amr';

        // 指定抓取的文件保存名称
        list($err) = $bucketManager->fetch($url, $bucket, $key);

        if ($err !== null) {

            // 转码
            // $auth = new Auth($accessKey, $secretKey);

            // 要转码的文件所在的空间和文件名。
            // $key = $key;

            // 转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
            $pipeline = 'qimeng';

            // 转码完成后通知到你的业务服务器。
            // $notifyUrl = 'http://375dec79.ngrok.com/notify.php';
            // $notifyUrl = url('index/api/voicenotify');
            // $notifyUrl = 'http://wx007.imwork.net/index/api/voicenotify';
            $notifyUrl = request()->domain() . '/index/api/voicenotify';
            $force = false;

            $config = new \Qiniu\Config();
            $config->useHTTPS = true;
            $pfop = new PersistentFop($auth, $config);

            // 要进行视频截图操作

            $fops = "avthumb/mp3/ab/128k/ar/44100/acodec/libmp3lame|saveas/" .
                \Qiniu\base64_urlSafeEncode($bucket . ":$key_name.mp3");

            list($id, $err2) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);

            return $err['key'];
        } else {
            return false;
        }

        $arr = $this->downloadWeixinFile($url);
        $file_name = time() . rand(0000, 9999) . '.amr';
        return $this->saveWeixinFile($file_name, $arr['body']);

    }


    /**
     *
     */
    public function getTempFile($id)
    {
        $this->access_token = $this->getAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $this->access_token . "&media_id=" . $id;

        $qn_config = Db::name('option')->where('option_name', 'qiniu')->value('option_value');
        $qn_config = json_decode($qn_config, true);

        // 使用七牛抓取
        $accessKey  = $qn_config['ak'];
        $secretKey  = $qn_config['sk'];
        $bucket     = $qn_config['bk'];

        $auth = new Auth($accessKey, $secretKey);
        $bucketManager = new BucketManager($auth);

        $key = date('Ymd', time()) . '/' . $id . '.jpg';

        // 指定抓取的文件保存名称
        list($err) = $bucketManager->fetch($url, $bucket, $key);

        if ($err !== null) {

            // 七牛样式处理
            $q_thumb = "?imageMogr2/auto-orient/thumbnail/!320x240r/gravity/Center/crop/320x240/quality/100/interlace/0";
            $f_name = $qn_config['domain'] . '/' . $err['key'];
            $f_name2 = $qn_config['domain'] . '/' . $f_name . $q_thumb;
            return ['url' => $f_name2, 'src' => $f_name];
        } else {
            return false;
        }

    }


    /**
     *
     */
    public function downloadWeixinFile($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
        return $imageAll;
    }


    /**
     *
     */
    public function saveWeixinFile2($filecontent)
    {
        $filename2 = $filename = time() . rand(0000, 9999) . '.jpg';

        // 动态的创建一个文件夹
        $path = date('Ymd');
        $save_path = $_SERVER['DOCUMENT_ROOT'] . "/live/" . $path;

        // 判断该文件夹是否已经有这个文件夹
        if (!file_exists($save_path)) {
            mkdir($save_path);
        }

        $filename = $save_path . '/' . $filename;

        try {

            $local_file = fopen($filename, 'w');
            if (false !== $local_file) {
                if (false !== fwrite($local_file, $filecontent)) {
                    fclose($local_file);
                }
            }

            return '/live/' . $path . '/' . $filename2;
        } catch (Exception $exception) {

            return false;
        }

        return false;
    }


    /**
     * 获取微信配置信息
     */
    public function js_config($url)
    {
        $jsapi_ticket = $this->getTicket();

        if (!$jsapi_ticket) {
            echo 'ticket error';
            die;
        }

        $noncestr   = "Wm3WZYTPz0wz" . rand(0000, 9999);
        $timestamp  = time();
        $sha1_str   = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $signature  = sha1($sha1_str);

        $config = [];
        $config['timestamp']    = $timestamp;
        $config['noncestr']     = $noncestr;
        $config['signature']    = $signature;
        $config['appId']        = $this->appid;

        return $config;
    }


    /**
     *
     */
    public function _auth($back_url)
    {
        $wxConfig = config('weixin');
        $wx_appid = $wxConfig['appid'];
        $back_url = urlencode($back_url);
        $login_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$wx_appid&redirect_uri=$back_url&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        $this->redirect($login_url);

    }

    /**
     * 主回调
     */
    public function _oauth($suc_url, $err_url)
    {
        try {
            $weixin = new Weixin();
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$weixin->appid&secret=$weixin->appsecret&code=" . $_GET['code'] . "&grant_type=authorization_code";
            $res = $weixin->https_request($url);
            $res = (json_decode($res, true));
            $row = $weixin->get_user_info($res['openid']);
            \session('wx', $row);
            $this->redirect($suc_url);

        } catch (Exception $exception) {

            $this->redirect($err_url);

        }


    }


    /**
     * 获取用户基本信息
     */
    public function get_user_info($openid)
    {
        $this->access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->access_token . "&openid=" . $openid . "&lang=zh_CN";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    /**
     * https请求
     */
    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}